package cn.j229.bug.zhongxuan.hualian.controller;

import cn.j229.bug.zhongxuan.hualian.pojo.Ticket;
import cn.j229.bug.zhongxuan.hualian.service.TicketService;
import cn.j229.bug.zhongxuan.hualian.utils.JsonResult;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @Author smile_ZhongXuan
 * @Date 2020/10/20 9:50
 * @Version 1.0
 */

@RestController
@RequestMapping("/ticket")
public class TicketController {
    @Resource
    TicketService ticketService = null;
    JsonResult jsonResult = new JsonResult();

    @PostMapping("/addTicket")
    @ResponseBody
    public Map addTicket(@RequestBody Ticket ticket){
        // 通过TicketService完成操作
        int addTicketSelective = ticketService.addTicketSelective(ticket);
        jsonResult.setCode("200");
        jsonResult.setMsg("优惠券添加成功！successful："+addTicketSelective);
        return jsonResult.getValues();
    }

    @PostMapping("/findAllTicketByPage")
    @ResponseBody
    public Map findAllTicketByPage(@RequestParam("page") Integer page,@RequestParam("size") Integer size){
        Map ticketServiceAllTicketByPage = ticketService.findAllTicketByPage(page, size);
        jsonResult.setData(ticketServiceAllTicketByPage);
        jsonResult.setCode("200");
        jsonResult.setMsg("优惠券列表查询成功");
        return jsonResult.getValues();
    }

    @GetMapping("/exportTicketList")
    @ResponseBody
    public Map exportTicketList(HttpServletResponse response) throws Exception {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
        String fileName = ticketService.exportTicketList(hssfWorkbook);
        //返回给前端下载
        response.setContentType("application/octet-stream");
        // 以附件形式访问
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        hssfWorkbook.write(response.getOutputStream());
        return jsonResult.getValues();
    }

    @PostMapping("/updateTicketState")
    public Map updateTicketState(@RequestBody Ticket ticket){
        int updateTicketState = ticketService.updateTicketState(ticket);
        jsonResult.setCode("200");
        jsonResult.setMsg("优惠券状态修改成功");
        return jsonResult.getValues();
    }
}
